<?php

class ItemsEditModel extends AuthModel
{
	private $oItemList;
	private $oEditItem;
	
	public function __construct()
	{
		parent::__construct();
		
		$this->oEditItem = null;
		
		if (Input::hasRequest("action"))
		{
			$action = Input::request("action");
			if ($action == "add")
			{
				$name = strip_tags(Input::request("name"));
				$desc = strip_tags(Input::request("desc"));
				$makePoints = floatval(Input::request("make_points"));
				$type = intval(Input::request("type"));
				
				do{
					if ($makePoints <= 0.0)
					{
						$this->addError("make_points", "ITEM_ERROR_MAKE_POINTS");
						break;
					}
					
					if ($type < 0 || $type > 1)
					{
						$this->addError("type", "ITEM_ERROR_TYPE");
						break;
					}
					
					$item = new ItemObject(array());
					$item->setName($name);
					$item->setDesc($desc);
					$item->setMakePoints($makePoints);
					$item->setType($type);
					
					ItemRegistry::i()->add($item);
					
					$this->setMsg(array("text" => "ADDED_NEW_ITEM", "item" => $item));
					
				} while (false);
			}
			else if ($action == "remove")
			{
				$id = Input::request("id");
			
				do{
					if (is_null($id)) break;
				
					$item = ItemRegistry::i()->byId($id);
					
					if (is_null($item)) break;
					
					ItemRegistry::i()->removeById($id);
					$this->setMsg(array("text" => "REMOVED_ITEM", "item" => $item));
					
				} while (false);
			}
			else if ($action == "edit")
			{
				$id = Input::request("id");
				$this->oEditItem = ItemRegistry::i()->byId($id);
				
				do{
					
					
					if (!Input::hasRequest("name")) break;
									
					$name = strip_tags(Input::request("name"));
					$desc = strip_tags(Input::request("desc"));
					$makePoints = floatval(Input::request("make_points"));
					$type = intval(Input::request("type"));
				
					$item = ItemRegistry::i()->byId($id);
					
					if (is_null($item))
						break;
					
					if ($makePoints <= 0.0)
					{
						$this->addError("make_points", "ITEM_ERROR_MAKE_POINTS");
						break;
					}
						
					if ($type < 0 || $type > 1)
					{
						$this->addError("type", "ITEM_ERROR_TYPE");
						break;
					}
					
					$item->setName($name);
					$item->setDesc($desc);
					$item->setMakePoints($makePoints);
					$item->setType($type);
					$this->oEditItem = null;
					
				} while(false);
			}
		}
		
		$this->oItemList = ItemRegistry::i()->itemList();
		asort($this->oItemList);
	}
	
	public function itemList() { return $this->oItemList; }
	
	public function editItem() { return $this->oEditItem; }
}

?>